package com.yksj.healthtalk.ui.dictionary;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.server.ServerShopSeachActivity;

/**
 * 
 * 显示具体的内容
 * @author zhao
 *
 */
public class DictionaryContentActivity extends BaseFragmentActivity implements OnClickListener {
	
	ExpandableListView mExpandableListView;
	DictionaryExpandableListAdapter mAdapter;
	String code;
	String type;
	String titleName;
	String resultData;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.dictionary_content_layout);
		
		code = getIntent().getStringExtra("parame");
		type = getIntent().getStringExtra("type");
		titleName = getIntent().getStringExtra("title");
		resultData = getIntent().getStringExtra("result");
		
		initView();
		
		initData();
	}
	
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		}
	};
	
	private void initView(){
		initTitle();
//		titleLeftBtn.setBackgroundResource(R.drawable.doctorbook_back);
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText(titleName);
		
		mExpandableListView = (ExpandableListView)findViewById(android.R.id.list);
		mExpandableListView.setAdapter(mAdapter = new DictionaryExpandableListAdapter(this));
		mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				return true;
			}
		});
	}
	
	/**
	 * 
	 * 初始化数据
	 * 
	 */
	private void initData(){
		if(resultData != null){//有数据直接显示
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(resultData);
				onParseResultData(jsonObject);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}else{
			if("1".equals(type)){
				HttpRestClient.doHttpQuerySituations(null, code,null, responseHandler);
			}else if("4".equals(type)){//科室
				HttpRestClient.doHttpQueryOfficesServlet(code, responseHandler);
			}else if("10001".equals(type) || "10002".equals(type) || "10003".equals(type)){
				HttpRestClient.doHttpQueryDiseasesServlet(null, null, code,null,null,null,responseHandler);
			}else if("10004".equals(type)||"10005".equals(type) ||"10006".equals(type)){
				HttpRestClient.doHttpQueryMedicinesServlet(null, null, code, null,null,responseHandler);
			}else if("10006".equals(type)||"10007".equals(type) ||"10008".equals(type)){
				//HttpRestClient.doHttpQueryMedicinesServlet(null, null, code, responseHandler);
			}else if("10015".equals(type) || "10016".equals(type)){
				HttpRestClient.doHttpSeeDoctorServlet(null, null, null, null, null, code, null, responseHandler);
			}else if("10013".equals(type) || "10014".equals(type)){//手术
				HttpRestClient.doHttpQueryTreatmentsServlet(null, null, code, null, responseHandler);
			}
		}
	}
	
	/**
	 * 解析数据
	 * @param response
	 */
	private void onParseResultData(JSONObject response){
		if(response != null){  
			try {
				response = response.getJSONObject("data");
				if(response.has("INFO")){
					final List<String> groupList = new ArrayList<String>();
					final List<String> childList = new ArrayList<String>();
						JSONArray jsonArray = response.getJSONArray("INFO");
						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject jsonObject = jsonArray.optJSONObject(i);
							String title = jsonObject.optString("menucode");
							String content = jsonObject.optString("menuname");
							//if(content.equals("n"))continue;//等于n不给予显示
							groupList.add(title);
							if("null".equals(content)) content = "内容近期将会更新,请随时关注!";
							childList.add(content);
						}
					mAdapter.onDataChange(groupList, childList);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	final JsonHttpResponseHandler responseHandler = new JsonHttpResponseHandler(this){
		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			super.onSuccess(statusCode, response);
			onParseResultData(response);
		}
		@Override
		public void onFailure(Throwable error, String content) {
			super.onFailure(error, content);
		}
	};
	
	
	private class DictionaryExpandableListAdapter extends BaseExpandableListAdapter{
		final List<String> groupList = new ArrayList<String>();
		final List<Object> childList = new ArrayList<Object>();
		final LayoutInflater mInflater;
		
		public DictionaryExpandableListAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}
		
		private void onDataChange(List<String> groupList,List<String> childList){
			this.groupList.addAll(groupList);
			this.childList.addAll(childList);
			for (int i = 0; i < groupList.size(); i++) {
				mExpandableListView.expandGroup(i);
			}
			notifyDataSetChanged();
		}
		
		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return groupList.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			// TODO Auto-generated method stub
			return 1;
		}

		@Override
		public String getGroup(int groupPosition) {
			// TODO Auto-generated method stub
			return groupList.get(groupPosition);
		}

		@Override
		public CharSequence getChild(int groupPosition, int childPosition) {
			Object object = childList.get(groupPosition);
			object = onParseATag((String)(object));
			/*
			if(object instanceof String){
				object = onParseATag((String)(object));
				childList.set(childPosition,object);
			}*/
			return (CharSequence)object;
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}
		

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			TextView textView = null;
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.dictionary_content_group_title, null);
			}
			textView = (TextView)convertView;
			
			textView.setTextColor(getResources().getColor(android.R.color.black));
			String title = getGroup(groupPosition);
			textView.setText(title);
			return convertView;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.dictionary_group_title, null);
				((TextView)convertView).setMovementMethod(LinkMovementMethod.getInstance());
			}
			TextView textView = (TextView)convertView;
			CharSequence charSequence = getChild(groupPosition,childPosition);
			if(charSequence != null)textView.setText(charSequence);
			return textView;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}
	
	/**
	 * 解析数据
	 * @param str
	 * @return
	 */
	private SpannableStringBuilder onParseATag(String str){
		SpannableStringBuilder builder = new SpannableStringBuilder(str);
		String pattern = "<a[^>]*>([\\d\\D]*?)</a>";
		Pattern p = Pattern.compile(pattern); 
		Matcher matcher = p.matcher(builder);
		
		while(matcher.find()){
			int start = matcher.start();
			int end = matcher.end();
			String str1 = matcher.group(1);
			SpannableString string = new SpannableString(str1);
			ATagClickSpand span = new ATagClickSpand(str1);
			string.setSpan(span,0,str1.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			builder.replace(start, end, string);
			matcher = p.matcher(builder);
		}
		return builder;
	}
	
	/**
	 * 药品连接
	 * @author zhao
	 *
	 */
	class ATagClickSpand extends ClickableSpan{
		String mStr;
		public ATagClickSpand(String str) {
			this.mStr = str;
		}
		@Override
		public void onClick(View widget) {
			Intent intent = new Intent(DictionaryContentActivity.this,ServerShopSeachActivity.class);
			intent.putExtra("name",mStr);
			intent.putExtra("type",-1);
			intent.putExtra("id", "-1");
			startActivity(intent);
		}
	}
	
}
